package com.pd.kit;

import java.util.Map;
import java.util.TreeMap;

/**
 * @author: dong peng
 * @date: 2018/4/9 11:48
 * @description:
 */

public class WxSignature {

    /**
     * eg:  appid=123&mchid=m123
     * @description 按key排序，然后以&拼接
     * @auth dong peng
     * @param params
     * @return
     */
    public static String joinStr(Map<String,String> params) {
        StringBuilder sb = new StringBuilder();

        if(!(params instanceof TreeMap)) {
            TreeMap map = new TreeMap();
            map.putAll(params);
            params = map;
        }

        boolean first = true;
        for (Map.Entry<String, String> entry : params.entrySet()) {
            if(entry.getValue() == null) {
                continue;
            }

            if(first) {
                first = false;
            }else {
                sb.append("&");
            }

            sb.append(entry.getKey())
                    .append("=")
                    .append(entry.getValue());
        }
        return sb.toString();
    }

    /**
     *
     * @param signKey   key=8934e7d15453e97507ef794cf7b0519d
     * @return
     */
    public static String signByMd5(Map<String,String> reqMap, String signKey) {
        String reqStr = joinStr(reqMap);
        String signTemp = reqStr +"&key="+ signKey;
        return MD5.createSign(signTemp).toUpperCase();
    }

    /**
     * md5验签
     * @param signMsg
     * @param reqMap
     * @param key
     * @return
     */
    public static Boolean checkSignMd5(String signMsg, Map<String,String> reqMap, String key) {
        String reqStr = joinStr(reqMap);
        String signTemp = reqStr +"&key="+ key;
        return MD5.checkSign(signTemp,signMsg);
    }


}
